package com.tod.security.springsecuritydbencrypt.service.impl;

import com.tod.security.springsecuritydbencrypt.constant.RoleConstant;
import com.tod.security.springsecuritydbencrypt.entity.UserEntity;
import com.tod.security.springsecuritydbencrypt.mapper.UserMapper;
import com.tod.security.springsecuritydbencrypt.service.UserService;
import com.tod.security.springsecuritydbencrypt.util.SpringContextHolder;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Tod.xie
 * Date: 2018-02-05
 * Time: 10:39
 *
 * @author Tod.xie
 */
@Service
@Primary
@Log4j
@AllArgsConstructor
public class BaseUserService implements UserService {

    private final UserMapper userMapper;

    @Override
    public boolean insert(UserEntity userEntity) {
        String username = userEntity.getUsername();
        if (exist(username)){
            return false;
        }
        userEntity.setPassword(SpringContextHolder.getBean(PasswordEncoder.class).encode(userEntity.getPassword()));
        userEntity.setRoles(RoleConstant.ROLE_USER);
        int result = userMapper.insert(userEntity);
        return  result == 1;
    }

    @Override
    public UserEntity getByUsername(String username) {
        return userMapper.selectByUsername(username);
    }

    /**
     * 判断用户是否存在
     * @param username 账号
     * @return 密码
     */
    private boolean exist(String username){
        UserEntity userEntity = userMapper.selectByUsername(username);
        return (userEntity != null);
    }
}
